package com.unfbx.chatgptsteamoutput.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Arrays;
import java.util.Random;

@Slf4j
@RestController
public class AudioController {

    @GetMapping(value = "/audio0", produces = "text/event-stream")
    public Flux<ServerSentEvent<byte[]>> getAudioStream0() {
        Random random = new Random();
        byte[] audioData = new byte[1024];
        random.nextBytes(audioData);

        return Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> ServerSentEvent.<byte[]>builder()
                        .id(String.valueOf(sequence))
                        .event("audio")
                        .data(audioData)
                        .build());
    }

    @GetMapping(value = "/audio", produces = "text/event-stream")
    public Flux<ServerSentEvent<byte[]>> getAudioStream() throws IOException {
        Path path = Paths.get("f:\\wind.mp3"); // 替换为您的MP3文件路径
        byte[] buffer = new byte[1024 * 10]; // 每次读取10KB
        int count = 0;
        return Flux.interval(Duration.ofSeconds(10)) // 每10秒发送一次音频数据
                .map(sequence -> {

                    try (InputStream inputStream = Files.newInputStream(path)) {
                        inputStream.skip(sequence * buffer.length); // 跳过已经发送的数据
                        int bytesRead = inputStream.read(buffer); // 读取音频数据
                        if (bytesRead == -1) { // 到达文件结尾
                            return ServerSentEvent.<byte[]>builder()
                                    .event("end")
                                    .build();
                        } else {

                            byte[] audioData = Arrays.copyOf(buffer, bytesRead); // 复制实际读取的数据
                            log.info(audioData.toString());
                            return ServerSentEvent.<byte[]>builder()
                                    .id(String.valueOf(sequence))
                                    .event("audio")
                                    .data(audioData)
                                    .build();
                        }
                    } catch (IOException e) {
                        return ServerSentEvent.<byte[]>builder()
                                .event("error")
                                .data(e.getMessage().getBytes())
                                .build();
                    }
                });
    }
}